/* $RCSFile: OptionsEdit2.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.ECommerce/PageModules/ProductOptions/OptionsEdit2.ascx.cs $
 * $log$
 * Revision 21 2010/08/09 11:08:12  christian.surieux
 *   Added Log comment to all .ascx .aspx .master files
 * Revision 8 2010/08/09 10:07:05  christian.surieux
 *   Added Log comment to all cs files
 */

using System;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Globalization;

using AddonNice.Diagnostics;
using AddonNice.ECommerce;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;
using Path2     =   AddonNice.Settings.Path;

namespace AddonNice.PageModules.ProductOptions
{

	public partial class OptionsEdit2 : UserControl
	{
		protected XmlDocument xmlOptionsDoc;

		// to use several of these controls for the same product
		protected string _optionName;
		public string OptionName
		{
			set
			{
				_optionName = value;
			}
			get
			{
				return _optionName;
			}
		}

		string _optionString                =   string.Empty;
		public string OptionString
		{
			get 
			{
                if (_optionString == string.Empty)
                {
                    object ob               =   ViewState["optionString"];
                    if (ob == null)
                        return string.Empty;
                    _optionString           =   (string)ob;
                }
				return _optionString; 
			}
			set 
			{ 
				ViewState["optionString"]   =   value; 
                _optionString               =   value;
			}
		}

		void Page_Load(object sender, EventArgs e)
		{
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OptionsEdit2 Page_Load BEG _optionString: {0}, IsPostBack: {1}, OptionName: {2}.",_optionString,IsPostBack,OptionName),ModuleTraceSwitch.Sw.Info);
			// Put user code to initialize the page here
			//Get the xml Document of Options

			//This will make sure that xmlOptionsDoc is not null and current
			xmlOptionsDoc   =   GetOptionsXml(OptionString);
			if( !IsPostBack )
				DisplayOptions();
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]OptionsEdit2 Page_Load END.",ModuleTraceSwitch.Sw.Info);
		}

		protected void btnAddOption_Click(object sender, System.EventArgs e)
		{
            if (ProductOptionsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OptionsEdit2 btnAddOption_Click BEG OptionName: '{0}'.",OptionName),ProductOptionsTrace.Sw.Info);
			//Add the value in newOptionsBox to the xmlOptionsDoc
			//This will add a new option into the list box and xml file
			string tempOption               =   newOptionBox.Text.Trim();
			//check to make sure a value exists before processing
			if( !string.IsNullOrEmpty(tempOption) )
			{
				//Make sure the option does not already exist
				//Create a search String for the option we are going to delete
				string searchString         =   string.Format("{0}/{1}[value='{2}']",EComStStr.ProductOptions,OptionName,tempOption);
				XmlNode foundNode           =   xmlOptionsDoc.SelectSingleNode(searchString);
                bool found  =   ( foundNode != null );
                if (ProductOptionsTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OptionsEdit2 btnAddOption_Click END OptionName: '{0}', tempOption: {1}, found: {2}.",
                        OptionName,tempOption,found),ProductOptionsTrace.Sw.Info);
				if( !found )
				{
					XmlNodeList nodeList    =   xmlOptionsDoc.GetElementsByTagName(EComStStr.ProductOptions);
					XmlElement option       =   xmlOptionsDoc.CreateElement(OptionName);
					XmlElement optionValue  =   xmlOptionsDoc.CreateElement("value");
					optionValue.InnerText   =   tempOption;
					option.AppendChild(optionValue);
					nodeList.Item(0).AppendChild(option);
					//Clear the text box for new entry
					newOptionBox.Text       =   string.Empty;
					DisplayOptions();
				}
			}
            if (ProductOptionsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OptionsEdit2 btnAddOption_Click END OptionName: '{0}', tempOption: {1}.",OptionName,tempOption),ProductOptionsTrace.Sw.Info);
		}

		protected void btnDeleteOption_Click(object sender, EventArgs e)
		{
            if (ProductOptionsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OptionsEdit2 btnDeleteOption_Click BEG OptionName: '{0}'.",OptionName),ProductOptionsTrace.Sw.Info);
			//Create a search String for the option we are going to delete
		    string searchString         =   string.Format("{0}/{1}[value='{2}']",EComStStr.ProductOptions,OptionName,lbOptions.SelectedItem);
			XmlNode foundNode       =   xmlOptionsDoc.SelectSingleNode(searchString);
			//Only try to delete if it exists
            bool found              =   (foundNode != null);
			if( found )
			{
				xmlOptionsDoc[EComStStr.ProductOptions].RemoveChild(foundNode);
				//Refresh the listbox
				DisplayOptions();
			}
            if (ProductOptionsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OptionsEdit2 btnDeleteOption_Click END OptionName: '{0}', found: {1}.",OptionName,found),ProductOptionsTrace.Sw.Info);
		}

		#region options methods
		
        string GetXmlString()
		{
            if (ProductOptionsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OptionsEdit2 GetXmlString BEG myXmlDoc.OuterXml: '{0}'.",xmlOptionsDoc.OuterXml),ProductOptionsTrace.Sw.Info);
			string searchString		=   EComStStr.ProductOptions;
			string xmlString		=   string.Empty;
			XmlNode foundNode		=   xmlOptionsDoc.SelectSingleNode(searchString);
			if(foundNode != null)
				xmlString			=   foundNode.OuterXml;
            if (ProductOptionsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OptionsEdit2 GetXmlString END xmlString: '{0}'.",xmlString),ProductOptionsTrace.Sw.Info);
			return xmlString;
		}

        /// <summary>
        /// Recreate a document with the list box content to be sure to keep only necessary options
        /// </summary>
        public string ExtractResultXmlString()
		{
            if (ProductOptionsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OptionsEdit2 ExtractResultXmlString BEG optionName: {0}.",OptionName),ProductOptionsTrace.Sw.Info);
			XmlDocument myXmlDoc    =   new XmlDocument();
		    //Now create the root Element
			XmlElement newRoot      =   myXmlDoc.CreateElement(EComStStr.ProductOptions);
    	    myXmlDoc.AppendChild(newRoot);
            foreach (ListItem item in lbOptions.Items)
            {
			    XmlElement opt      =   myXmlDoc.CreateElement(OptionName);
                newRoot.AppendChild(opt);
                XmlElement node     =   myXmlDoc.CreateElement("value");
                node.InnerText      =   item.Value;
                opt.AppendChild(node);
            }
			string xmlString		=   myXmlDoc.InnerXml;
            if (ProductOptionsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OptionsEdit2 ExtractResultXmlString END optionName: {0}, xmlString: '{1}'.",OptionName,xmlString),ProductOptionsTrace.Sw.Info);
			return xmlString;
		}

        /// <summary>
		/// protected XmlDocument GetOptionsXml(string)
		/// provide a string representing an xml file or null for a new document
		/// </summary>
		XmlDocument GetOptionsXml(string myXmlString)
		{
            if (ProductOptionsTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OptionsEdit2 GetOptionsXml BEG myXmlString: '{0}'.",myXmlString),ProductOptionsTrace.Sw.Info);
			//Create a xml Document
			XmlDocument myXmlDoc    =   new XmlDocument();
            try
            {
                // Load or create document
			    if( string.IsNullOrEmpty(myXmlString) )
			    {
				    XmlElement newRoot      =   myXmlDoc.CreateElement(EComStStr.ProductOptions);
				    myXmlDoc.AppendChild(newRoot);	
			    }
			    else
			    {
				    myXmlDoc.LoadXml(myXmlString);
			    }
                if (ProductOptionsTrace.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]OptionsEdit2 GetOptionsXml END myXmlDoc.OuterXml: '{0}'.",myXmlDoc.OuterXml),ProductOptionsTrace.Sw.Info);
            }
            catch(Exception ex)
            {
                if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]OptionsEdit2 GetOptionsXml ex: {0}.",ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
			//myXmlDoc is either populated or an empty Xml formated file
			return myXmlDoc;
		}

		/// <summary>
		/// fill the options in the listbox
		/// </summary>
		void DisplayOptions()
		{
			lbOptions.Items.Clear();
			
            XmlNodeList nodeList    =   xmlOptionsDoc.GetElementsByTagName(OptionName);
            foreach (XmlNode node in nodeList)
            {
                if ( node["value"] != null )
                    lbOptions.Items.Add(node["value"].InnerText);
            }
			//Now refresh the optionString with the updated values
			OptionString            =   GetXmlString();
		}

		#endregion

        #region Std Overrides

		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
		}
		
		private void InitializeComponent()
		{
            Load                    +=  new EventHandler(Page_Load);
            btnAddOption.Click      +=  new EventHandler(btnAddOption_Click);
            btnDeleteOption.Click   +=  new EventHandler(btnDeleteOption_Click);
        }

		#endregion

	}
}
